<template>
  <div class="tags-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>标签管理</h2>
        <p>管理博客文章标签，包括创建、编辑、删除等操作</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="showCreateDialog">
          <el-icon><Plus /></el-icon>
          新建标签
        </el-button>
      </div>
    </div>
    <!-- 搜索和筛选 -->
    <div class="search-section">
      <el-card>
        <el-form :inline="true" @submit.prevent>
          <el-form-item label="搜索标签名">
            <el-input
              v-model="searchName"
              placeholder="搜索标签名"
              clearable
              @keyup.enter="fetchTags"
              style="width: 220px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchTags">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <!-- 标签列表 -->
    <div class="tags-list">
      <el-card>
        <el-table
          v-loading="loading"
          :data="tags"
          style="width: 100%"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="名称" min-width="120" />
          <el-table-column prop="slug" label="别名" min-width="120" />
          <el-table-column prop="articles_count" label="文章数" width="100" />
          <el-table-column prop="created_at" label="创建时间" min-width="160">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="editTag(row)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteTag(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="pagination.current_page"
            v-model:page-size="pagination.per_page"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建/编辑标签对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑标签' : '新建标签'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标签名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入标签名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="别名" prop="slug">
          <el-input
            v-model="form.slug"
            placeholder="请输入别名（英文）"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTag" :loading="saving">
            {{ isEdit ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { tagApi } from '@/api/admin'

// 搜索关键字
const searchName = ref('')
// 标签列表
const tags = ref([])
const loading = ref(false)

// 分页
const pagination = ref({
  current_page: 1,
  per_page: 10,
  total: 0
})

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const editingId = ref(null)

// 表单引用
const formRef = ref(null)

// 表单数据
const form = ref({
  name: '',
  slug: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入标签名称', trigger: 'blur' },
    { min: 2, max: 50, message: '标签名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  slug: [
    { required: true, message: '请输入别名', trigger: 'blur' },
    { pattern: /^[a-z0-9-]+$/, message: '别名只能包含小写字母、数字和连字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取标签列表
const fetchTags = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.current_page,
      per_page: pagination.value.per_page
    }
    if (searchName.value) params.search = searchName.value
    const response = await tagApi.getTags(params)
    console.log(response)
    tags.value = response.data || []
    pagination.value = {
      current_page: response.meta.current_page,
      per_page: response.meta.per_page,
      total: response.meta.total
    }
  } catch (error) {
    ElMessage.error('获取标签列表失败')
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size) => {
  pagination.value.per_page = size
  pagination.value.current_page = 1
  fetchTags()
}

const handleCurrentChange = (page) => {
  pagination.value.current_page = page
  fetchTags()
}

// 显示创建对话框
const showCreateDialog = () => {
  isEdit.value = false
  editingId.value = null
  form.value = {
    name: '',
    slug: ''
  }
  dialogVisible.value = true
}

// 编辑标签
const editTag = (tag) => {
  isEdit.value = true
  editingId.value = tag.id
  form.value = {
    name: tag.name,
    slug: tag.slug
  }
  dialogVisible.value = true
}

// 保存标签
const saveTag = async () => {
  try {
    await formRef.value.validate()
    saving.value = true
    if (isEdit.value) {
      await tagApi.updateTag(editingId.value, form.value)
      ElMessage.success('标签更新成功')
    } else {
      await tagApi.createTag(form.value)
      ElMessage.success('标签创建成功')
    }
    dialogVisible.value = false
    fetchTags()
    form.value = { name: '', slug: '' }
    isEdit.value = false
    editingId.value = null
  } catch (error) {
    if (error !== false) {
      ElMessage.error('保存标签失败')
    }
  } finally {
    saving.value = false
  }
}

// 删除标签
const deleteTag = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个标签吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await tagApi.deleteTag(id)
    ElMessage.success('删除成功')
    fetchTags()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除标签失败')
    }
  }
}

onMounted(() => {
  fetchTags()
})
</script>

<style scoped lang="scss">
.tags-page {
  .search-section {
    margin-bottom: 24px;
  }
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 24px;

    .header-left {
      h2 {
        margin: 0 0 8px 0;
        font-size: 24px;
        color: #303133;
      }

      p {
        margin: 0;
        color: #909399;
        font-size: 14px;
      }
    }
  }
  .pagination-wrapper {
    margin-top: 24px;
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .tags-page {
    .page-header {
      flex-direction: column;
      gap: 16px;

      .header-right {
        align-self: stretch;
      }
    }
  }
}
</style> 